package com.yx.utils;

import org.apache.commons.io.FileUtils;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.POIXMLTextExtractor;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/** 文本内容读取工具类
 * Created by wuye on 2017/12/4.
 */
public class ContextUtil {

    public static String fileReadUtil(MultipartFile filetext) throws IOException {
        File file = new File(filetext.getOriginalFilename());

        FileUtils.copyInputStreamToFile(filetext.getInputStream(), file);

        String path = file.getAbsolutePath();
        String s = "";
        try {
            if(path.endsWith(".doc")) {
                // InputStream is = new FileInputStream(new File(path));
                InputStream is = new FileInputStream(path);
                WordExtractor ex = new WordExtractor(is);
                s = ex.getText();
            }else if (path.endsWith(".docx")) {
                OPCPackage opcPackage = POIXMLDocument.openPackage(path);
                POIXMLTextExtractor extractor = new XWPFWordExtractor(opcPackage);
                s = extractor.getText();
            }else if(path.endsWith("txt")){
                String encoding = "GBK";
                Long filelength = file.length();
                byte[] filecontent = new byte[filelength.intValue()];
                try {
                    FileInputStream in = new FileInputStream(file);
                    in.read(filecontent);
                    in.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                try {
                    return new String(filecontent, encoding);
                } catch (UnsupportedEncodingException e) {
                    System.err.println("The OS does not support " + encoding);
                    e.printStackTrace();
                    return null;
                }
            }else {
                System.out.println("传入的word文件不正确:"+path);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        StringBuffer bf = new StringBuffer(s);
        return bf.toString();
    }
}
